import {
  createRouter,
  createWebHashHistory,
  RouteRecordRaw, // 路由类型（可以 ctrl 大法进到 vue-router 内看类型）
} from 'vue-router';
import { localCache, firstRoute } from '@/utils';

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main',
  },

  {
    path: '/login',
    name: 'login',
    component: () =>
      import(/* webpackChunkName: "login" */ '@/views/login/Login'),
  },

  {
    path: '/main',
    name: 'main',
    component: () =>
      import(/* webpackChunkName: "main" */ '@/views/main/Main.vue'),
    children: [],
  },

  {
    path: '/:pathMatch(.*)*',
    name: '404',
    component: () => import('@/views/404/404.vue'),
  },
];

const router = createRouter({
  routes,
  history: createWebHashHistory(),
});

const whiteRouter = ['/login'];

router.beforeEach((to) => {
  const { path } = to;

  if (!whiteRouter.includes(path)) {
    if (!localCache.getCache('token')) {
      return '/login';
    }
  }

  if (to.path === '/main') {
    if (firstRoute) {
      return firstRoute.path;
    }
  }

  return true;
});

export default router;
